package com.graduate.daydayup.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.AlarmClock
import android.util.Log
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.graduate.daydayup.App
import com.graduate.daydayup.R
import com.graduate.daydayup.base.BaseActivity
import com.graduate.daydayup.room.MyRoomDataBase
import com.graduate.daydayup.room.Schedule
import com.graduate.daydayup.util.DateFormatUtil
import com.graduate.daydayup.util.ExcelUtil
import com.graduate.daydayup.view.MyPickerView
import com.graduate.daydayup.view.PickerViewHelper
import kotlinx.android.synthetic.main.activity_lessonset.*
import java.util.*
import kotlin.collections.ArrayList
import kotlin.random.Random


class LessonSettingAtivity :BaseActivity() {
    val default="8:20,\n9:15,\n10:15,\n11:10,\n13:00,\n13:55,\n14:50,\n16:45,\n18:30,\n19:25,\n20:20"
    private val FILE_SELECTOR_CODE = 10000
    override fun setTitle()="课表设置"



    override fun getLayout()= R.layout.activity_lessonset
    override fun setTextRight()=""

    override fun setImgRightListener() {


    }

    override fun isAddToolbar()=true

    override fun initViewIds() {
        if (SPUtils.getInstance().getString("currentterm")!=null&&!SPUtils.getInstance().getString("currentterm").isEmpty()){
            stv_cuterm.setRightString(
                SPUtils.getInstance().getString("currentterm").replace(
                    "00:00:00",
                    ""
                )
            )
        }
        if (SPUtils.getInstance().getInt("currentweek")!=-1){
            stv_week.setRightString("第" + SPUtils.getInstance().getInt("currentweek") + "周")
        }
        if (SPUtils.getInstance().getString("originweek")!=null&&!SPUtils.getInstance().getString("originweek").isEmpty()){
            stv_orginweek.setRightString(SPUtils.getInstance().getString("originweek"))
        }
        if (SPUtils.getInstance().getString("lessonremind")!=null&&!SPUtils.getInstance().getString(
                "lessonremind"
            ).isEmpty()){
            stv_lesson_remind.setRightString(SPUtils.getInstance().getString("lessonremind"))
        }
        if (SPUtils.getInstance().getInt("lessoncounts")!=-1){
            stv_lesson_counts.setRightString("${SPUtils.getInstance().getInt("lessoncounts")}节")
        }else{
            stv_lesson_counts.setRightString("8节")

        }
    }

    override fun initView() {
        var listItemWeek=ArrayList<String>()
        val pickview_currentweek= MyPickerView(this)
        var listItem1=ArrayList<String>()
        val pickview_orginweek= MyPickerView(this)
        var listItem2=ArrayList<String>()
        val pickview_lessoncounts= MyPickerView(this)
        val pickview_lessonremind= MyPickerView(this)
        //TODO 开学时间
        stv_cuterm.setOnClickListener{
            PickerViewHelper().showTimePicker(
                this,
                booleanArrayOf(true, true, true, false, false, false),
                0,
                1
            ) { timeStamp ->
                SPUtils.getInstance().put(
                    "currentterm",
                    DateFormatUtil.timestampToDate(timeStamp) + " 00:00:00"
                )
                stv_cuterm.setRightString(DateFormatUtil.timestampToDate(timeStamp))
            }
        }
        for (i in 1..20){
            listItemWeek.add("第" + i.toString() + "周")
        }
        pickview_currentweek.setPicker(listItemWeek)
        stv_week.setOnSuperTextViewClickListener {
            pickview_currentweek.show()
        }
        pickview_currentweek.setOnoptionsSelectListener { options1, option2, options3 ->
            stv_week.setRightString(listItemWeek[options1])
            SPUtils.getInstance().put("currentweek", options1 + 1)
        }
        //TODO 周起始日
        listItem1.add("周一")
        listItem1.add("周二")
        listItem1.add("周三")
        listItem1.add("周四")
        listItem1.add("周五")
        listItem1.add("周六")
        listItem1.add("周日")
        pickview_orginweek.setPicker(listItem1)
        stv_orginweek.setOnSuperTextViewClickListener {
            pickview_orginweek.show()
        }
        pickview_orginweek.setOnoptionsSelectListener { options1, option2, options3 ->
            stv_orginweek.setRightString(listItem1[options1])
            SPUtils.getInstance().put("originweek", listItem1[options1])
        }
        //TODO 课程节数
        for (i in 8..20){
            listItem2.add(i.toString() + "节")
        }
        pickview_lessoncounts.setPicker(listItem2)
        stv_lesson_counts.setOnSuperTextViewClickListener {
            pickview_lessoncounts.show()
        }
        pickview_lessoncounts.setOnoptionsSelectListener { options1, option2, options3 ->
            stv_lesson_counts.setRightString(listItem2[options1])
            SPUtils.getInstance().put("lessoncounts", options1 + 8)
        }
        stv_lesson_time.setOnSuperTextViewClickListener {
            val view=LayoutInflater.from(this).inflate(R.layout.dialog_lesson_time, null)
            val dialog = AlertDialog.Builder(this).setView(view).create()
            val etTime = view.findViewById<EditText>(R.id.et_time)
            if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString(
                    "lessontime"
                ).isEmpty()) {
                etTime.setText(SPUtils.getInstance().getString("lessontime"))
            }else{
                etTime.setText(default)
            }
            view.findViewById<Button>(R.id.btn_sure).setOnClickListener {
                if (etTime.text.toString().isEmpty()){
                    ToastUtils.showShort("上课时间为空")
                }else{
                    SPUtils.getInstance().put("lessontime", etTime.text.toString())
                    dialog.dismiss()
                    ToastUtils.showShort("设置时间成功")
                }

            }
            view.findViewById<Button>(R.id.btn_cancel).setOnClickListener {
                dialog.dismiss()
            }

            dialog.setCancelable(false)
            dialog.show()
        }

        tv_add.setOnClickListener {
            ActivityUtils.startActivity(LessonAddActivity::class.java)
        }
        //TODO 上课提醒
        var listItem5=ArrayList<String>()
        listItem5.add("不提醒")
        listItem5.add("15分钟前提醒")
        listItem5.add("30分钟前提醒")
        listItem5.add("1小时前提醒")
        pickview_lessonremind.setPicker(listItem5)
        stv_lesson_remind.setOnSuperTextViewClickListener {
            ActivityUtils.startActivity(Intent(AlarmClock.ACTION_SHOW_ALARMS))
        }
        pickview_lessonremind.setOnoptionsSelectListener { options1, option2, options3 ->
            stv_lesson_remind.setRightString(listItem5[options1])
            SPUtils.getInstance().put("lessonremind", listItem5[options1])
            //TODO 设置闹钟
            val list=MyRoomDataBase.getInstance(App.instance!!).scheduleDao().getAll()
            if (list != null) {
                for (bean in list){
                    var   start = bean.start
                    if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString(
                            "lessontime"
                        ).isEmpty()){
                        val replace = SPUtils.getInstance().getString("lessontime").replace(
                            "\n",
                            ""
                        )
                        val split = replace.split(",")
                        val split1 = split[start].split(":")
                        Log.d("设置闹钟", split1[0] + split1[1])
                        setSystemAlarmClock(this, bean.name, split1[0].toInt(), split1[1].toInt())
                    }else{
                        val replace = default.replace("\n", "")
                        val split = replace.split(",")
                        val split1 = split[start].split(":")
                        Log.d("设置闹钟", split1[0] + split1[1])
                        setSystemAlarmClock(
                            this,
                            "在${bean.room}上${bean.teacher}的${bean.name}",
                            split1[0].toInt(),
                            split1[1].toInt()
                        )
                    }
                }
            }


        }
        //TODO 导入课程excel
        tv_exceladd.setOnClickListener {
            openFileSelector()
        }

    }

    /**
     * 打开本地文件器选择文件
     */
    private fun openFileSelector() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "*/*" //设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        startActivityForResult(intent, FILE_SELECTOR_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == FILE_SELECTOR_CODE && resultCode == RESULT_OK) {
            val uri = data!!.data ?: return
            Log.i("拿到数据", "onActivityResult: " + "文件路径：" + uri.path)
            //选择文件，然后导入
            importExcelDeal(uri)
        }
    }

    private fun importExcelDeal(uri: Uri){
        val readExcelNew = ExcelUtil.readExcelNew(this, uri, uri.path)
        val week1 = arrayListOf<String>()
        val week2 = arrayListOf<String>()
        val week3 = arrayListOf<String>()
        val week4 = arrayListOf<String>()
        val week5 = arrayListOf<String>()
        val week6 = arrayListOf<String>()
        val week7 = arrayListOf<String>()
        for (bean in readExcelNew){
            if (bean[1].toString().isNotEmpty()){
                week1.add(bean[1].toString())
            }
            if (bean[2].toString().isNotEmpty()){
                week2.add(bean[2].toString())
            }
            if (bean[3].toString().isNotEmpty()){
                week3.add(bean[3].toString())
            }
            if (bean[4].toString().isNotEmpty()){
                week4.add(bean[4].toString())
            }
            if (bean[5].toString().isNotEmpty()){
                week5.add(bean[5].toString())
            }
            if (bean[6].toString().isNotEmpty()){
                week6.add(bean[6].toString())
            }
            if (bean[7].toString().isNotEmpty()){
                week7.add(bean[7].toString())
            }
        }
        MyRoomDataBase.getInstance(this).scheduleDao().deleteAllBy()
        getFilterData(week1)
        getFilterData(week2)
        getFilterData(week3)
        getFilterData(week4)
        getFilterData(week5)
        getFilterData(week6)
        getFilterData(week7)
        ToastUtils.showShort("导入成功")

    }




    private fun getFilterData(list:ArrayList<String>){
        if (list.size>0){
            val listSchedule = mutableListOf<Schedule>()
            list.removeAt(0)

            for (b1 in list){
                if (b1!=null&&b1!="null"){
                    val s1 = b1.replace("\n","").split(";")
                    for (b2 in s1){
                        var schedule = Schedule(0, "", "", "", "", 0, 0, 0, 0)
                        val s2 = b2.split(",")
                        //TODO 课程名称
                        schedule.name=s2[0]
                        //TODO 授课老师
                        schedule.teacher=s2[1]
                        //TODO 第几周到第几周
                        schedule.weeklist= s2[2].replace("-",",").replace("周","")
                        //TODO 周几
                        schedule.day=getIntFromWeekString(s2[3])
                        //TODO 第几节
                        val split = s2[4].replace("节","").split("-")

                        schedule.start=split[0].toInt()
                        schedule.step=split[1].toInt()- schedule.start+1

                        //TODO 位置
                        schedule.room=s2[5]
                        val random = Random(10)
                        schedule.colorRandom=random.nextInt()
                        MyRoomDataBase.getInstance(this).scheduleDao().addSchedule(schedule)
                    }
                }

            }
        }

    }

    //TODO 批量设置闹钟
    fun setClockMore(schedule: Schedule){
        if (SPUtils.getInstance().getString("lessontime")!=null&&!SPUtils.getInstance().getString("lessontime").isEmpty()){
            val replace = SPUtils.getInstance().getString("lessontime").replace("\n", "")
            val split = replace.split(",")
            val split1 = split[schedule.start - 1].split(":")
            Log.d("设置闹钟", split1[0] + split1[1])
            setSystemAlarmClock(
                    this,
                    "在${schedule.room}上${schedule.teacher}的${schedule.name}",
                    schedule.day,
                    split1[0].toInt(),
                    split1[1].toInt()
            )
        }else{
            val replace = default.replace("\n", "")
            val split = replace.split(",")
            val split1 = split[schedule.start - 1].split(":")
            Log.d("设置闹钟", split1[0] + split1[1])
            setSystemAlarmClock(
                    this,
                    "在${schedule.room}上${schedule.teacher}的${schedule.name}",
                    schedule. day,
                    split1[0].toInt(),
                    split1[1].toInt()
            )
        }
    }

    fun setSystemAlarmClock(context: Context, message: String?, days: Int, hour: Int, minute: Int): Boolean {
        if (Build.VERSION.SDK_INT < 9) {
            return false
        }
        val testDays: ArrayList<Int> = ArrayList()
        when(days){
            1->testDays.add(Calendar.MONDAY)
            2->testDays.add(Calendar.TUESDAY)
            3->testDays.add(Calendar.WEDNESDAY)
            4->testDays.add(Calendar.THURSDAY)
            5->testDays.add(Calendar.FRIDAY)
            6->testDays.add(Calendar.SATURDAY)
            7->testDays.add(Calendar.SUNDAY)
        }
        val intent = Intent(AlarmClock.ACTION_SET_ALARM)
        intent.putExtra(AlarmClock.EXTRA_MESSAGE, message)
        intent.putExtra(AlarmClock.EXTRA_DAYS, testDays)
        intent.putExtra(AlarmClock.EXTRA_HOUR, hour)
        intent.putExtra(AlarmClock.EXTRA_MINUTES, minute)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 11) {
            intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
        }
        if (Build.VERSION.SDK_INT >= 19) {
            intent.putExtra(AlarmClock.EXTRA_VIBRATE, true)
        }
        return try {
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    fun getIntFromWeekString(week:String):Int{
        var weekInt=0
        when(week){
            "周一"->weekInt=1
            "周二"->weekInt=2
            "周三"->weekInt=3
            "周四"->weekInt=4
            "周五"->weekInt=5
            "周六"->weekInt=6
            "周日"->weekInt=7

        }
        return weekInt
    }

    @SuppressLint("WrongConstant")
    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun setSystemAlarmClock(context: Context, message: String?, hour: Int, minute: Int): Boolean {

        if (Build.VERSION.SDK_INT < 9) {
            return false
        }
        val intent = Intent(AlarmClock.ACTION_SET_ALARM)
        intent.putExtra(AlarmClock.EXTRA_MESSAGE, message)
        intent.putExtra(AlarmClock.EXTRA_HOUR, hour)
        intent.putExtra(AlarmClock.EXTRA_MINUTES, minute)
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 11) {
            intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
        }
        if (Build.VERSION.SDK_INT >= 19) {
            intent.putExtra(AlarmClock.EXTRA_VIBRATE, true)
        }
        return try {
            context.startActivity(intent)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

}